package com.cloud.order.service.impl;

import com.cloud.order.bean.Order;
import com.cloud.order.feign.ProductFeignClient;
import com.cloud.order.service.OrderService;
import com.cloud.product.bean.Product;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * @author lx
 * @date 2025/11/11
 * @Description
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private LoadBalancerClient loadBalancerClient;
    @Resource
    ProductFeignClient productFeignClient;
    @Override
    public Order creatOrder(Long userId,Long productId) {
        Product product = productFeignClient.getProduct(productId,"");
        return new Order(4L, userId,new BigDecimal(100), Arrays.asList(product));
    }

    private Product getProductFromRemote(Long id) {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + id;
        log.info("远程调用url:{} " + url);

        return restTemplate.getForObject(url, Product.class);
    }

    private Product getProductFromRemoteWithLoadBalancer(Long id) {
        ServiceInstance instance = loadBalancerClient.choose("service-product");
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + id;
        log.info("远程调用url:{} " + url);

        return restTemplate.getForObject(url, Product.class);
    }

    private Product getProductFromRemoteWithLoadBalancerAndAnnotation(Long id) {
        String url = "http://service-product/product/" + id;
        log.info("远程调用url:{} " + url);

        return restTemplate.getForObject(url, Product.class);
    }
}
